﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Super.Admin.Views.ShowDialog
{
    public partial class FrmAlert : AntdUI.Window
    {
        // 静态变量跟踪所有打开的窗体实例
        private static readonly List<FrmAlert> openWindows = new List<FrmAlert>();
        private static readonly object lockObj = new object();
        private const int Spacing = 10; // 窗体间距
        private CancellationTokenSource _cts;
        private Point _assignedLocation;
        public FrmAlert()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.Manual; // 手动设置位置
            TopMost = true;
            ShowInTaskbar = false; // 不显示在任务栏
            this.Load += FrmAlert_Load;
            this.FormClosed += (s, e) => {
                _cts?.Cancel();
                RemoveFromOpenWindows();
            };
        }

        private async void FrmAlert_Load(object? sender, EventArgs e)
        {
            // 设置窗体位置
            CalculatePosition();
            // 添加到打开窗体列表
            lock (lockObj)
            {
                openWindows.Add(this);
            }
            // 3秒后自动关闭
            _cts = new CancellationTokenSource();
            try
            {
                await Task.Delay(3000, _cts.Token);
                if (!this.IsDisposed)
                {
                    this.Invoke(() => this.Close());
                }
            }
            catch (TaskCanceledException) { }
        }

        private void CalculatePosition()
        {
            lock (lockObj)
            {
                // 获取主屏幕工作区域
                var screen = Screen.PrimaryScreen?.WorkingArea ?? Screen.PrimaryScreen.Bounds;
                int right = screen.Right;
                int top = screen.Top;
                // 默认位置：右上角
                int x = right - this.Width - Spacing;
                int y = top + Spacing;
                // 查找当前占用位置
                var occupiedPositions = openWindows
                    .Where(w => w != this)
                    .Select(w => w._assignedLocation)
                    .ToList();
                // 查找可用的Y位置
                foreach (var loc in occupiedPositions.OrderBy(p => p.Y))
                {
                    // 检查是否在相同列（水平位置接近）
                    if (Math.Abs(loc.X - x) < this.Width)
                    {
                        // 放在现有窗体下方
                        y = Math.Max(y, loc.Y + this.Height + Spacing);
                    }
                }
                // 检查是否超出屏幕底部
                if (y + this.Height > screen.Bottom)
                {
                    // 尝试左侧位置
                    x = screen.Left + Spacing;
                    y = top + Spacing;

                    // 重新计算左侧位置
                    foreach (var loc in occupiedPositions.OrderBy(p => p.Y))
                    {
                        if (Math.Abs(loc.X - x) < this.Width)
                        {
                            y = Math.Max(y, loc.Y + this.Height + Spacing);
                        }
                    }
                }
                _assignedLocation = new Point(x, y);
                this.Location = _assignedLocation;
            }
        }

        private void RemoveFromOpenWindows()
        {
            lock (lockObj)
            {
                openWindows.Remove(this);
            }
        }
    }
}
